/* Copyright (c) 2004-2024 peigen.info. All rights reserved. */

package info.peigen.hotpot.business.account.manage.repository.service;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import info.peigen.hotpot.business.account.core.domain.account.Account;
import info.peigen.hotpot.business.account.core.repository.entity.AccountEntity;
import info.peigen.hotpot.business.account.manage.convertor.AccountManageConvertor;
import info.peigen.hotpot.business.account.manage.repository.mapper.AccountManageMapper;
import info.peigen.hotpot.common.core.result.ResultCode;
import info.peigen.hotpot.common.service.base.exception.BusinessException;
import info.peigen.hotpot.component.data.repository.beetlsql.service.AbstractBeetlSqlRepository;
import org.noear.solon.annotation.Component;

/**
 * <b>(AccountManageRepository)</b>
 * 管理后台 "账户" 仓储服务
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2023-08-29
 */
@SuppressWarnings("unused")
@Component
public class AccountManageRepository extends AbstractBeetlSqlRepository<AccountManageMapper, AccountEntity> {

    public Account active(String accountId) {
        Assert.isTrue(StrUtil.isNotEmpty(accountId), () -> new BusinessException(ResultCode.FAILURE, "激活时[accountId]不得为空!"));

        AccountEntity entity = getMapper().findByAccountId(accountId);

        Assert.notNull(entity, () -> new BusinessException(ResultCode.FAILURE, "激活失败!accountId=" + accountId));

        return AccountManageConvertor.convertToDomain(entity);
    }

    public Account lock(String accountId) {
        Assert.isTrue(StrUtil.isNotEmpty(accountId), () -> new BusinessException(ResultCode.FAILURE, "加锁时[accountId]不得为空!"));

        AccountEntity entity = getMapper().lockByAccountId(accountId);

        Assert.notNull(entity, () -> new BusinessException(ResultCode.FAILURE, "锁定失败!accountId为空!"));

        return AccountManageConvertor.convertToDomain(entity);
    }

    public void removeByAccountId(String accountId) {
        Assert.isTrue(StrUtil.isNotEmpty(accountId), () -> new BusinessException(ResultCode.FAILURE, "删除时[accountId]不得为空!"));

        getMapper().deleteByAccountId(accountId);
    }

    public void store(Account domain) {
        Assert.isTrue(ObjectUtil.isNotEmpty(domain), () -> new BusinessException(ResultCode.FAILURE, "持久化时[domain]不得为空!"));

        AccountEntity entity = AccountManageConvertor.convertToEntity(domain);

        saveOrUpdate(entity);
    }
}